package org.example.monitor;

public class ThreadLocalTest {

    public static void main(String[] args) {
        Resources resources = new Resources("mytest1", "mytest2");
        // 若没出现，多试几次
        Thread thread1 = new Thread(new ThreadA(resources), "threadA");
        Thread thread2 = new Thread(new ThreadB(resources), "threadB");
        thread1.start();
        thread2.start();
    }
}

class Resources{
    public String s1;

    public String s2;

    public Resources(String s1 ,String s2){
        this.s1 = s1;
        this.s2 = s2;

    }
}
class ThreadA implements Runnable{
    private Resources resources;

    public ThreadA(Resources resources){
        this.resources = resources;
    }


    @Override
    public void run() {
        synchronized (resources.s1){
            System.out.println(Thread.currentThread().getName()+"获得s1资源");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (resources.s2){
                System.out.println(Thread.currentThread().getName()+"获得s2资源");
            }
        }
    }
}

class ThreadB implements Runnable{
    private Resources resources;

    public ThreadB(Resources resources){
        this.resources = resources;
    }


    @Override
    public void run() {
        synchronized (resources.s2){
            System.out.println(Thread.currentThread().getName()+"获得s2资源");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (resources.s1){
                System.out.println(Thread.currentThread().getName()+"获得s2资源");
            }
        }
    }
}